﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;

namespace ImageWater
{
    class InitFile
    {

        public bool isauto =bool.Parse(ConfigurationManager.AppSettings["IsAuto"].ToString());
        public Image GetImage(string url)
        {
            Image image = null;
            try
            {
                WebRequest request = WebRequest.Create(url);
                WebResponse response = request.GetResponse();
                
                Stream s = response.GetResponseStream();
                byte[] data = new byte[1024];
                int length = 0;
                MemoryStream ms = new MemoryStream();
                while ((length = s.Read(data, 0, data.Length)) > 0)
                {
                    ms.Write(data, 0, length);
                }
                ms.Seek(0, SeekOrigin.Begin);               
                image = Image.FromStream(ms);
                //return Image.FromStream(ms);
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString(), true);              
            }
            return image;
        }

        /// <summary>
        /// 列出指定目录下及所其有子目录及子目录里更深层目录里的文件（需要递归） 
        /// </summary>
        /// <param name="path"></param>
        /// <param name="FolderName"></param>
        /// <returns></returns>
        public string GetAllFiles(string SouFolderName, string FolderName = "")
        {
            try
            {
                string result = "";
                DirectoryInfo dir = new DirectoryInfo(SouFolderName);

                //找到该目录下的文件  
                FileInfo[] fi = dir.GetFiles();
                foreach (FileInfo f in fi)
                {
                    string p = f.FullName.ToString();
                    p = p.Substring(p.LastIndexOf(SouFolderName) + FolderName.Length).ToString();
                    p = p.Replace("\\", "/");
                }
                //找到该目录下的所有目录再递归  
                DirectoryInfo[] subDir = dir.GetDirectories();
                foreach (DirectoryInfo d in subDir)
                {
                    result += GetAllFiles(d.FullName, FolderName);
                }
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        //TIF 转 JPG
        /// <summary>
        /// TIF 转 JPG
        /// </summary>
        /// <param name="tiffFileName">TIF文件位置</param>
        /// <param name="jpegFileName">生成文件位置</param>
        public void ConvertTiff2Jpeg(string tiffFileName, string jpegFileName)
        {
            var img = Image.FromFile(tiffFileName);
            var count = img.GetFrameCount(FrameDimension.Page);
            for (int i = 0; i < count; i++)
            {
                img.SelectActiveFrame(FrameDimension.Page, i);
                img.Save(jpegFileName + ".part" + i + ".jpg");
            }
            int imageWidth = img.Width;
            int imageHeight = img.Height * count;
            Bitmap joinedBitmap = new Bitmap(imageWidth, imageHeight);
            Graphics graphics = Graphics.FromImage(joinedBitmap);
            for (int i = 0; i < count; i++)
            {
                var partImageFileName = jpegFileName + ".part" + i + ".jpg";
                Image partImage = Image.FromFile(partImageFileName);
                graphics.DrawImage(partImage, 0, partImage.Height * i, partImage.Width, partImage.Height);
                partImage.Dispose();
                File.Delete(partImageFileName);
            }
            joinedBitmap.Save(jpegFileName);

            graphics.Dispose();
            joinedBitmap.Dispose();
            img.Dispose();

            //return jpegFileName;
        }

        #region 日志
        /// <summary>
        /// 生成日志文件
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isdebug"></param>
        public void WriteLog(string msg, bool isdebug)
        {
            string text = AppDomain.CurrentDomain.BaseDirectory;
            text = Path.Combine(text, "log");
            if (!Directory.Exists(text))
            {
                Directory.CreateDirectory(text);
            }
            if (isdebug)
            {
                text = Path.Combine(text, "debug");
                if (!Directory.Exists(text))
                {
                    Directory.CreateDirectory(text);
                }
            }
            text = Path.Combine(text, DateTime.Now.ToString("yyyyMMdd") + ".txt");
            if (!File.Exists(text))
            {
                File.CreateText(text).Close();
            }
            StreamWriter streamWriter = new StreamWriter(text, true, Encoding.UTF8);
            if (isdebug)
            {
                streamWriter.WriteLine("--------------------------------------------------------------------------------------------------------------------------------");
            }
            streamWriter.WriteLine("{0}  {1}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"), msg);
            if (isdebug)
            {
                streamWriter.WriteLine("--------------------------------------------------------------------------------------------------------------------------------");
            }
            streamWriter.Flush();
            streamWriter.Close();
        }
        /// <summary>
        /// 清理日志文件
        /// </summary>
        public void ClearLog()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
            if (Directory.Exists(path))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories);
                FileInfo[] array = files;
                for (int i = 0; i < array.Length; i++)
                {
                    FileInfo fileInfo = array[i];
                    if (DateTime.Now.Subtract(fileInfo.CreationTime).Days > 30)
                    {
                        File.Delete(fileInfo.FullName);
                    }
                }
            }
        }
        #endregion
    }
}
